import base64
import time

ak = 'c27fe9a9-e3b0-4d8b-8132-9eaf61286431'
sk = 'BoReRxcncocmnbn_y-6yjYv_Ng796QXkz0ywCSeV5HVMhId-7ay8IJ0W9zRyzCMtMCfXwAerTT3IOiwvcJ4lfA'


def get_walmart_token(service_name='hunan'):
    url = 'https://marketplace.walmartapis.com/v3/token'
    auth_string = f'{ak}:{sk}'
    auth_base64 = base64.b64encode(auth_string.encode('utf-8')).decode('utf-8')
    headers = {
        'WM_QOS.CORRELATION_ID': str(time.time()),
        'WM_SVC.NAME': service_name,
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json',
        'Authorization': f'Basic {auth_base64}'
    }
    data = {'grant_type': 'client_credentials'}
    try:
        response = requests.post(url, headers=headers, data=data, timeout=30)
        if response.status_code == 200:
            return response.json()["access_token"]
        else:
            print(f"Error getting token: {response.status_code} - {response.text}")
    except Exception as e:
        print(f"Error getting token: {e}")


import requests


def get_walmart_items(access_token, service_name='hunan', next_cursor="*", sku=None, gtin=None, offset=0, limit=20, lifecycle_status=None, published_status=None, variant_group_id=None, condition=None, availability=None, show_duplicate_item_info=False):
    url = 'https://marketplace.walmartapis.com/v3/items'
    headers = {
        'WM_SEC.ACCESS_TOKEN': access_token,
        'WM_QOS.CORRELATION_ID': str(time.time()),
        'WM_SVC.NAME': service_name,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    params = {
        'nextCursor': next_cursor,
        'sku': sku,
        'gtin': gtin,
        'offset': offset,
        'limit': limit,
        'lifecycleStatus': lifecycle_status,
        'publishedStatus': published_status,
        'variantGroupId': variant_group_id,
        'condition': condition,
        'availability': availability,
        'showDuplicateItemInfo': str(show_duplicate_item_info).lower()
    }
    params = {key: value for key, value in params.items() if value is not None}
    try:
        response = requests.get(url, headers=headers, params=params, timeout=30)
        if response.status_code == 200:
            return response.json()["ItemResponse"]
        else:
            print(f"Error fetching items: {response.status_code} - {response.text}")
    except Exception as e:
        print(f"Error getting items: {e}")


if __name__ == '__main__':
    token = get_walmart_token()
    items = get_walmart_items(token)
    for item in items:
        print(item)
